import logging
from PyQt5.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QPushButton, QFileDialog, QMessageBox, QLabel, QLineEdit,
    QStatusBar, QSpacerItem, QSizePolicy, QFrame, QCheckBox, QButtonGroup, QRadioButton
)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from pathlib import Path
from services.image_processor import ImageProcessor

# Configure logger
logger = logging.getLogger(__name__)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("图片水印添加器")
        self.setMinimumSize(650, 550)  # 稍微增加高度以适应新控件
        
        # 创建主窗口部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # 添加标题标签
        title_label = QLabel("图片水印添加工具")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setFont(QFont("微软雅黑", 16, QFont.Bold))
        main_layout.addWidget(title_label)
        
        # 添加分隔线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        main_layout.addWidget(line)
        
        # 创建选项布局（网格布局）
        options_layout = QGridLayout()
        
        # CSV 文件选择
        self.csv_file_label = QLabel("CSV文件:")
        self.csv_file_label.setFont(QFont("微软雅黑", 10))
        self.csv_file_line = QLineEdit()
        self.csv_file_line.setReadOnly(True)
        self.csv_file_line.setPlaceholderText("请选择准考证号与身份证号映射的CSV文件")
        self.csv_file_button = QPushButton("浏览...")
        self.csv_file_button.clicked.connect(self.select_csv_file)
        
        # 添加水印模式选择 - 改为使用单选按钮组
        watermark_mode_label = QLabel("水印模式:")
        watermark_mode_label.setFont(QFont("微软雅黑", 10))
        
        self.watermark_mode_group = QButtonGroup(self)
        
        self.single_watermark_radio = QRadioButton("单水印（仅显示身份证号）")
        self.single_watermark_radio.setFont(QFont("微软雅黑", 10))
        
        self.dual_watermark_radio = QRadioButton("双水印（身份证号 + 准考证号）")
        self.dual_watermark_radio.setFont(QFont("微软雅黑", 10))
        
        self.triple_watermark_radio = QRadioButton("三重水印（身份证号 + 准考证号 + 报名序号）")
        self.triple_watermark_radio.setFont(QFont("微软雅黑", 10))
        self.triple_watermark_radio.setChecked(True)  # 默认选中三重水印
        
        self.watermark_mode_group.addButton(self.single_watermark_radio, 1)
        self.watermark_mode_group.addButton(self.dual_watermark_radio, 2)
        self.watermark_mode_group.addButton(self.triple_watermark_radio, 3)
        
        # 添加控件到网格布局
        options_layout.addWidget(self.csv_file_label, 0, 0)
        options_layout.addWidget(self.csv_file_line, 0, 1)
        options_layout.addWidget(self.csv_file_button, 0, 2)
        
        options_layout.addWidget(watermark_mode_label, 1, 0)
        options_layout.addWidget(self.single_watermark_radio, 1, 1)
        options_layout.addWidget(self.dual_watermark_radio, 2, 1)
        options_layout.addWidget(self.triple_watermark_radio, 3, 1)
        
        # 添加选项布局到主布局
        main_layout.addLayout(options_layout)
        main_layout.addSpacing(10)
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        
        # 选择图片按钮
        self.select_button = QPushButton("选择图片")
        self.select_button.setMinimumSize(120, 40)
        self.select_button.setFont(QFont("微软雅黑", 10))
        self.select_button.clicked.connect(self.select_images)
        
        # 打开输出文件夹按钮
        self.open_output_button = QPushButton("打开输出文件夹")
        self.open_output_button.setMinimumSize(120, 40)
        self.open_output_button.setFont(QFont("微软雅黑", 10))
        self.open_output_button.clicked.connect(self.open_output_folder)
        
        # 关于按钮
        self.about_button = QPushButton("关于")
        self.about_button.setMinimumSize(120, 40)
        self.about_button.setFont(QFont("微软雅黑", 10))
        self.about_button.clicked.connect(self.show_about)
        
        # 添加按钮到布局
        button_layout.addStretch()
        button_layout.addWidget(self.select_button)
        button_layout.addWidget(self.open_output_button)
        button_layout.addWidget(self.about_button)
        button_layout.addStretch()
        
        # 添加按钮布局到主布局
        main_layout.addSpacing(10)
        main_layout.addLayout(button_layout)
        main_layout.addStretch()
        
        # 添加说明文本
        self.help_text = QLabel(
            "使用说明：\n"
            "1. 选择映射CSV文件（包含报名序号、准考证号与身份证号的映射关系）\n"
            "2. 选择水印模式（单、双或三重水印）\n"
            "3. 点击\"选择图片\"按钮，选择以身份证号命名的照片\n"
            "4. 程序将自动添加所选模式的水印\n"
            "5. 处理后的图片保存在output目录下的时间戳子文件夹中"
        )
        
        self.help_text.setStyleSheet("padding-left: 20px;")  # 直接设置样式表   # 20px的左内边距
        self.help_text.setAlignment(Qt.AlignLeft)  # 左对齐
        self.help_text.setFont(QFont("微软雅黑", 10))
        main_layout.addWidget(self.help_text)       #添加说明文本到主布局
        main_layout.addStretch()    # 添加伸缩空间以填充剩余空间

        # 添加状态栏
        self.statusBar = QStatusBar()
        self.setStatusBar(self.statusBar)
        self.statusBar.showMessage("准备就绪")
        
        # 保存CSV文件路径
        self.csv_file_path = ""
        
        # 初始化图片处理器
        self.image_processor = ImageProcessor()

    def select_csv_file(self):
        """选择CSV文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择CSV文件",
            "",
            "CSV文件 (*.csv);;所有文件 (*)"
        )
        
        if file_path:
            self.csv_file_path = file_path
            self.csv_file_line.setText(file_path)
            self.statusBar.showMessage(f"已选择CSV文件: {Path(file_path).name}")
        else:
            self.statusBar.showMessage("已取消选择CSV文件")

    def select_images(self):
        """选择图片并处理"""
        # 检查双水印或三重水印模式是否需要CSV文件
        watermark_mode = self.watermark_mode_group.checkedId()
        if (watermark_mode in [2, 3]) and not self.csv_file_path:
            QMessageBox.warning(self, "提示", "双水印和三重水印模式需要选择CSV文件！")
            self.statusBar.showMessage("请先选择CSV文件")
            return

        self.statusBar.showMessage("选择图片...")
        file_paths, _ = QFileDialog.getOpenFileNames(
            self,
            "选择图片",
            "",
            "图片文件 (*.png *.jpg *.jpeg *.bmp)"
        )
        
        if file_paths:
            self.process_images(file_paths)
        else:
            self.statusBar.showMessage("已取消选择")

    def process_images(self, image_paths):
        """处理选中的图片"""
        self.statusBar.showMessage("正在处理图片...")
        
        # 根据选择的模式处理图片
        watermark_mode = self.watermark_mode_group.checkedId()
        
        if watermark_mode == 3:
            # 三重水印模式
            success_count, error_count = self.image_processor.process_images_with_triple_watermarks(
                image_paths, self.csv_file_path
            )
            result_message = f"成功处理 {success_count}/{len(image_paths)} 张图片，失败 {error_count} 张"
            
        elif watermark_mode == 2:
            # 双水印模式
            success_count, error_count = self.image_processor.process_images_with_dual_watermarks(
                image_paths, self.csv_file_path
            )
            result_message = f"成功处理 {success_count}/{len(image_paths)} 张图片，失败 {error_count} 张"
            
        else:
            # 单水印模式
            success_count = 0
            for image_path in image_paths:
                if self.image_processor.add_watermark(image_path):
                    success_count += 1
            
            result_message = f"成功处理 {success_count}/{len(image_paths)} 张图片"
        
        self.statusBar.showMessage(result_message)
        QMessageBox.information(self, "处理完成", result_message)

    def open_output_folder(self):
        """打开最新的输出文件夹"""
        import os
        output_base = Path("output").absolute()
        
        try:
            # 获取最新的输出子目录
            latest_dir = max(
                [d for d in output_base.iterdir() if d.is_dir()],
                default=output_base,
                key=lambda x: x.stat().st_mtime
            )
            os.startfile(str(latest_dir))
            self.statusBar.showMessage(f"已打开输出文件夹: {latest_dir.name}")
        except Exception as e:
            self.statusBar.showMessage("打开输出文件夹失败")
            logger.error(f"打开输出文件夹失败: {e}")

    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(
            self,
            "关于图片水印添加器",
            "图片水印添加器 v3.0\n\n"
            "本程序可以批量为图片添加水印\n"
            "支持单水印、双水印和三重水印模式\n"
            "- 单水印：身份证号\n"
            "- 双水印：身份证号和准考证号\n"
            "- 三重水印：身份证号、准考证号和报名序号\n\n"
            "作者: 积极的风筝（堌阳1中）\n"
            "版权所有 © 2025"
        )
